<?php
class Shop_User_Mapping extends QDB_ActiveRecord_Abstract
{
	/**
	 * 返回对象的定义
	 *
	 * @static
	 *
	 * @return array
	 */
	static function __define()
	{
		return array
		(
			// 指定该 ActiveRecord 要使用的行为插件
			'behaviors' => '',

			// 指定行为插件的配置
			'behaviors_settings' => array
			(
			    # '插件名' => array('选项' => 设置),
			),

			// 用什么数据表保存对象
			'table_name' => 'shop_user_mapping',

			// 指定数据表记录字段与对象属性之间的映射关系
			// 没有在此处指定的属性，QeePHP 会自动设置将属性映射为对象的可读写属性
			'props' => array
			(
				// 主键应该是只读，确保领域对象的“不变量”
				'id' => array('readonly' => true),

				/**
				 *  可以在此添加其他属性的设置
				 */
				# 'other_prop' => array('readonly' => true),

				/**
				 * 添加对象间的关联
				 */
				# 'other' => array('has_one' => 'Class'),

			),

			/**
			 * 允许使用 mass-assignment 方式赋值的属性
			 *
			 * 如果指定了 attr_accessible，则忽略 attr_protected 的设置。
			 */
			'attr_accessible' => '',

			/**
			 * 拒绝使用 mass-assignment 方式赋值的属性
			 */
			'attr_protected' => 'id',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值不允许由外部提供
			 *
			 * 这里指定的属性会在创建记录时被过滤掉，从而让数据库自行填充值。
			 */
			'create_reject' => '',

			/**
			 * 指定更新数据库中的对象时，哪些属性的值不允许由外部提供
			 */
			'update_reject' => '',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 如果填充值为 self::AUTOFILL_TIMESTAMP 或 self::AUTOFILL_DATETIME，
			 * 则会根据属性的类型来自动填充当前时间（整数或字符串）。
			 *
			 * 如果填充值为一个数组，则假定为 callback 方法。
			 */
			'create_autofill' => array
			(
				# 属性名 => 填充值
				# 'is_locked' => 0,
			),

			/**
			 * 指定更新数据库中的对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 填充值的指定规则同 create_autofill
			 */
			'update_autofill' => array
			(
			),

			/**
			 * 在保存对象时，会按照下面指定的验证规则进行验证。验证失败会抛出异常。
			 *
			 * 除了在保存时自动验证，还可以通过对象的 ::meta()->validate() 方法对数组数据进行验证。
			 *
			 * 如果需要添加一个自定义验证，应该写成
			 *
			 * 'title' => array(
			 *	array(array(__CLASS__, 'checkTitle'), '标题不能为空'),
			 * )
			 *
			 * 然后在该类中添加 checkTitle() 方法。函数原型如下：
			 *
			 * static function checkTitle($title)
			 *
			 * 该方法返回 true 表示通过验证。
			 */
			'validations' => array
			(
			),
		);
	}


/* ------------------ 以下是自动生成的代码，不能修改 ------------------ */

	/**
	 * 开启一个查询，查找符合条件的对象或对象集合
	 *
	 * @static
	 *
	 * @return QDB_Select
	 */
	static function find()
	{
		$args = func_get_args();
		return QDB_ActiveRecord_Meta::instance(__CLASS__)->findByArgs($args);
	}

	/**
	 * 返回当前 ActiveRecord 类的元数据对象
	 *
	 * @static
	 *
	 * @return QDB_ActiveRecord_Meta
	 */
	static function meta()
	{
		return QDB_ActiveRecord_Meta::instance(__CLASS__);
	}


/* ------------------ 以上是自动生成的代码，不能修改 ------------------ */

	static function updateMapping($shop_ids, $user_id)
	{
		$mapping = Shop_User_Mapping::find('user_id=?', $user_id)->asArray()->getAll();
		$shop_old = array();
		foreach ($mapping as $m)
		{
			$shop_old[] = $m['shop_id'];
		}
		$shop_delete = array_diff($shop_old, $shop_ids);
		$shop_create = array_diff($shop_ids, $shop_old);
		if ($shop_delete)
		{
			Shop_User_mapping::meta()->deleteWhere('user_id=? and shop_id in (?)', $user_id, $shop_delete);
		}
		foreach ($shop_create as $sc)
		{
			QDB::getConn()->execute('insert into shop_user_mapping(user_id, shop_id) values(' . $user_id . ',' . $sc . ')');
		}
		Shop_User_Mapping::updateNextMapping($user_id);
		return array('ack' => SUCCESS, 'message' => '');
	}
	
	/*
	 * 获取树形结果店铺列表
	 * $platform 平台  ARRAY
	 * $user_id 用户ID
	 * $return shop_group
	 */
	static function getTreeShopByPlatform($platform = array(), $user_id = CURRENT_USER_ID)
	{
		$where = 'shop.status=' . Q::ini('custom_flag/shop_status/enabled/value') . ' and shop_user_mapping.user_id=' . $user_id;
		if ($platform)
		{
			$where .= ' and platform in (\'' . implode('\',\'', $platform) . '\')';
		}
		$shop = Shop_User_Mapping::find($where)
			->joinLeft('shop', '', 'shop.id=shop_user_mapping.shop_id')
			->setColumns('shop.*')->asArray()->getAll();
		$shop_group = array();
		foreach ($shop as $s)
		{
			$shop_group[$s['platform']][] = $s;
		}
		return $shop_group;
	}
	
	/*
	 * 获取店铺列表
	 * $platform 平台  STRING
	 * $user_id 用户ID
	 * $return shop
	 */
	static function getShopByPlatform($platform = 'ebay', $user_id = CURRENT_USER_ID)
	{
		$shop = Shop_User_Mapping::find('shop.status=? and shop.platform=? and shop_user_mapping.user_id=?', Q::ini('custom_flag/shop_status/enabled/value'), $platform, $user_id)
			->joinLeft('shop', '', 'shop.id=shop_user_mapping.shop_id')
			->setColumns('shop.*')->asArray()->getAll();
		return $shop;
	}
	
	static function getShopByUserId($user_id = CURRENT_USER_ID)
	{
		$shop = shop_User_Mapping::find('shop.status=? and shop_user_mapping.user_id=?', Q::ini('custom_flag/shop_status/enabled/value'), $user_id)
			->joinLeft('shop', '', 'shop.id=shop_user_mapping.shop_id')
			->setColumns('shop.*')->asArray()->getAll();
		return $shop;
	}
	
	static function getShopIdByUserId($user_id = CURRENT_USER_ID)
	{
		$shop_id = QDB::getConn()->execute('select shop_user_mapping.shop_id from shop_user_mapping left join shop on shop.id=shop_user_mapping.shop_id where shop_user_mapping.user_id=' . $user_id . ' and shop.status=' . Q::ini('custom_flag/shop_status/enabled/value'))->fetchCol();
		return $shop_id;
	}
	
	static function checkMapping($shop_id, $user_id = CURRENT_USER_ID)
	{
		if ( ! is_array($shop_id))
		{
			$shop_id = array($shop_id);
		}
		foreach ($shop_id as $s)
		{
			$mapping = Shop_User_Mapping::find('shop_id=? and user_id=?', $s, $user_id)->asArray()->getOne();
			if ( ! $mapping)
			{
				return array('ack' => FAILURE, 'message' => '用户没有店铺的管理权限');
			}
		}
		return array('ack' => SUCCESS, 'message' => '');
	}
	
	static function getUserShopId($user_id)
	{
		return QDB::getConn()->execute('select shop_id from shop_user_mapping where user_id=' . $user_id)->fetchCol();
	}
	
	static function updateNextMapping($user_id)
	{
		$child = User::find('parent_id=?', $user_id)->asArray()->getAll();
		$mapping = Shop_User_Mapping::getUserShopId($user_id);
		foreach ($child as $c)
		{
			$child_mapping = Shop_User_Mapping::getUserShopId($c['id']);
			foreach ($child_mapping as $cm)
			{
				if (! in_array($cm, $mapping))
				{
					Shop_User_Mapping::meta()->deleteWhere('user_id=? and shop_id=?', $c['id'], $cm);
				}
			}
			Shop_User_Mapping::updateNextMapping($c['id']);
		}
	}
	
	static function updateShopAllotUserByShop($shop_id, $user_ids)
	{
		$mapping = Shop_User_Mapping::find('shop_id=? and status=? and parent_id=? and type!=1', $shop_id, Q::ini('custom_flag/user_status/on_duty/value'), CURRENT_USER_ID)
			->joinLeft('user', '', 'user.id=shop_user_mapping.user_id')
			->asArray()->getAll();
		$user_ids_old = array();
		foreach($mapping as $m)
		{
			$user_ids_old[] = $m['user_id'];
		}
		$user_delete = array_diff($user_ids_old, $user_ids);
		$user_insert = array_diff($user_ids, $user_ids_old);
		if ($user_delete)
		{
			Shop_User_Mapping::meta()->deleteWhere('shop_id=? and user_id in (?)', $shop_id, $user_delete);
			foreach ($user_delete as $ud)
			{
				Shop_User_Mapping::updateNextMapping($ud);
			}
		}
		if ($user_insert)
		{
			foreach ($user_insert as $ui)
			{
				$shop_user_mapping = new Shop_User_Mapping();
				$shop_user_mapping->user_id = $ui;
				$shop_user_mapping->shop_id = $shop_id;
				$shop_user_mapping->save();
			}
		}
		return array('ack' => SUCCESS, 'message' => '');
	}
}